package com.example.william.globe;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.app.Activity;


public class GlobeActivity extends Activity implements OnTouchListener, SensorEventListener{

	static private float xTouch, yTouch;
	GlobeView g;
	boolean isRunning;
	static boolean onInitTouch;
	static boolean onTouch;
	TextView tv1, tv2, tv3;
	Thread back;
	Handler h = new Handler(){
		
		@Override
		public void handleMessage(Message m){
			if(onTouch){
			onTouch = false;
			}
			if(!onTouch){
				onTouch = true;
			}
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_globe);
        RelativeLayout rl = (RelativeLayout)findViewById(R.id.RelativeLayout);
        g = new GlobeView(this);
        g.setOnTouchListener(this);
        rl.addView(g);
        setXTouch(0);
        setYTouch(0);
        isRunning = false;
        onInitTouch = false;
        onTouch = false;
        tv1 = (TextView)findViewById(R.id.textView1);
        tv2 = (TextView)findViewById(R.id.textView2);
        tv3 = (TextView)findViewById(R.id.textView3);
    }

	public boolean onTouch(View v, MotionEvent event) {
		
		setXTouch(event.getX());
		setYTouch(event.getY());
		onInitTouch = true;
		onTouch = true;
		
		if(event.getAction()==MotionEvent.ACTION_UP){
		onInitTouch = false;
		onTouch = false;
		}
		tv1.setText("X: "+getXTouch());
		tv2.setText("Y: "+getYTouch());
		tv3.setText("Touched: "+onInitTouch);
		return true;
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		isRunning = false;
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		isRunning = true;
	}
	
	@Override
	protected void onStart(){
		super.onStart();
		
		back = new Thread(new Runnable(){
			public void run() {
				try{
					while(isRunning){
						Thread.sleep(500);
						if(onInitTouch){
						h.sendMessage(h.obtainMessage());
						}
					}
				}catch(Throwable t){System.err.println(t.getMessage());}
			}
		});
		isRunning = true;
		back.start();
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		
		
	}

	public void onSensorChanged(SensorEvent event) {
		
		
	}

	public static float getXTouch() {
		return xTouch;
	}

	public static void setXTouch(float xT) {
		xTouch = xT;
	}

	public static float getYTouch() {
		return yTouch;
	}

	public static void setYTouch(float yT) {
		yTouch = yT;
	}

}
